package com.yaolonga.itfc.manager.core;

import com.yaolonga.itfc.manager.core.exception.ValidateException;
import com.yaolonga.itfc.manager.core.utils.NetUtil;
import lombok.Builder;
import lombok.Data;

/**
 * @Author: yaolong
 * @CreateTime: 2024-10-24  13:51
 * @Description: 网络路由配置
 * @Version: 1.0
 */
@Data
public class NetRoute {

    /**
     * 接口名称
     *
     * @see NetworkInterfaceInfo#getName()
     */
    private String interfaceName;

    /**
     * 网关地址
     */
    private String gateway;
    /**
     * 目标网段
     */
    private String target;

    /**
     * 网络接口ip
     */
    private String ip;

    /**
     * 子网掩码
     */
    private String mask;

    /**
     * 网络接口索引
     */
    private Integer ifIndex;

    /**
     * 路由权重（跃点数）
     */
    private String metric;


    /**
     * 路由类型
     */
    private NetRouteType type;


    public boolean isSame(NetRoute route){
        return route.getTarget().equals(target) && route.getMask().equals(mask) && route.getGateway().equals(gateway) && route.getMetric().equals(metric);
    }

    /**
     * @return 是否默认路由
     */
    public Boolean isDefault() {
        return "0.0.0.0".equals(target);
    }

    /**
     * @return 目标网段和子网掩码
     */
    public String getTargetAndMask() {
        return target + "/" + NetUtil.getMaskNum(mask);
    }

    public void validate() {
        if (null == interfaceName){
            throw new ValidateException("接口名称不能为空");
        }

        if (null == gateway) {
            throw new ValidateException("网关地址不能为空");
        }

        if (null == target) {
            throw new ValidateException("目标网段地址不能为空");
        }

        if (null == mask) {
            throw new ValidateException("子网掩码不能为空");
        }

        String[] gatewayIp = gateway.split("\\.");
        for (String s : gatewayIp) {
            if (Integer.parseInt(s) < 0 || Integer.parseInt(s) > 255) {
                throw new ValidateException("网关地址格式错误：" + s);
            }
        }
        String[] netIP = target.split("\\.");
        for (String s : netIP) {
            if (Integer.parseInt(s) < 0 || Integer.parseInt(s) > 255) {
                throw new ValidateException("目标网段地址格式错误：" + s);
            }
        }

        String[] maskIp = mask.split("\\.");
        for (String s : maskIp) {
            if (Integer.parseInt(s) < 0 || Integer.parseInt(s) > 256) {
                throw new ValidateException("子网掩码地址格式错误：" + s);
            }
        }
    }
}
